package nocuffin.m5;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public class Map extends MapActivity implements LocationListener {
	/** Called when the activity is first created. */
	MapView map;
	long start;
	long stop;
	MyLocationOverlay compass;
	MapController controller;
	int x, y;
	GeoPoint touchedPoint, p;
	Drawable d;
	List<Overlay> overlayList;
	LocationManager lm;
	String towers, collected, name;
	int lat;
	int longi;
	Bundle b;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main7);
		map = (MapView) findViewById(R.id.map);
		map.setBuiltInZoomControls(true);

		Touchy t = new Touchy();
		overlayList = map.getOverlays();
		overlayList.add(t);
		compass = new MyLocationOverlay(Map.this, map);
		overlayList.add(compass);
		controller = map.getController();
		GeoPoint point = new GeoPoint(51643234, 7848593);
		controller.animateTo(point);
		controller.setZoom(2);
		b = getIntent().getExtras(); 
	    name = b.getString("name");
	    MapController mc = map.getController(); 
	
		d = getResources().getDrawable(R.drawable.ic_launcher);
		
		
		//Placing pinpoint at location
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria crit = new Criteria();
		
		towers = lm.getBestProvider(crit, false);
		Location location = lm.getLastKnownLocation(towers);
		
		if (location != null){
			lat = (int) (location.getLatitude() *1E6);
			longi = (int) (location.getLongitude() * 1E6);
			GeoPoint ourLocation = new GeoPoint(lat, longi);
			OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
			CustomPinpoint custom = new CustomPinpoint(d, Map.this);
			custom.insertPinpoint(overlayItem); 
			overlayList.add(custom);
		}else{
			//Toast.makeText(Map.this, "Loading...", Toast.LENGTH_SHORT).show();
		}
		
		findTasks(); 
		String[] entries = this.collected.split("\n");
		String[] csentries = new String[5];
		csentries[1] = "hj:g:k";
		int count = 0;
		for (int i=0; i < entries.length; i++)
		{
			if (entries[i].contains(name))
			{
				csentries[count] = entries[i];
				count++;
			}
			if (count == 4)
			{
				break;
			}
		}
		//Toast.makeText(Map.this, csentries[2], Toast.LENGTH_SHORT).show();
		if (csentries[1] != "hj:g:k")
		{
			for (int j = 1; j < count; j++)
			{
				if (!csentries[j].contains("now complete"))
				{
					//Toast.makeText(Map.this, csentries[j].split(":")[2], Toast.LENGTH_SHORT).show();

				}
			}	
		}
		Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
        try {
        	Toast.makeText(Map.this, "Loading...", Toast.LENGTH_SHORT).show();
        	for (int j = 1; j < count; j++)
        	{
            List<Address> addresses = geoCoder.getFromLocationName(
            		csentries[j].split(":")[2], 5);
            String add = "";
            if (addresses.size() > 0) {
                p = new GeoPoint(
                        (int) (addresses.get(0).getLatitude() * 1E6), 
                        (int) (addresses.get(0).getLongitude() * 1E6));
                OverlayItem overlayItem = new OverlayItem(p, "What's up", "2nd String");
				CustomPinpoint custom = new CustomPinpoint(d, Map.this);
				custom.insertPinpoint(overlayItem);
				overlayList.add(custom); 
            }    
        } 
        }catch (IOException e) {
            e.printStackTrace();
        }
        
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		compass.disableCompass();
		super.onPause();
		lm.removeUpdates(this);
		finish();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		compass.enableCompass();
		super.onResume();
		lm.requestLocationUpdates(towers, 500, 1, this);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	class Touchy extends Overlay {
		public boolean onTouchEvent(MotionEvent e, MapView m) {
			if (e.getAction() == MotionEvent.ACTION_DOWN) {
				start = e.getEventTime();
				x = (int) e.getX();
				y = (int) e.getY();
				touchedPoint = map.getProjection().fromPixels(x, y);
				
			}
			if (e.getAction() == MotionEvent.ACTION_UP) {
				stop = e.getEventTime();
			}
			if (stop - start > 1800) {
				AlertDialog alert = new AlertDialog.Builder(Map.this).create();
				alert.setTitle("Pick an Option");
				alert.setMessage("");
				alert.setButton("Pinpoint",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
						
								OverlayItem overlayItem = new OverlayItem(touchedPoint, "What's up", "2nd String");
								CustomPinpoint custom = new CustomPinpoint(d, Map.this);
								custom.insertPinpoint(overlayItem);
								overlayList.add(custom);
								map.invalidate();
								
								
								
								
							}
						});
				alert.setButton2("Get Address",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								
							Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
								try{
									
									List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() /1E6, touchedPoint.getLongitudeE6()/1E6, 1);							
								
									if (address.size() > 0){
										String display = "";												
										for (int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++){
											
											display += address.get(0).getAddressLine(i) + "\n";
										}
										Toast t3 = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
										t3.show();
									}
									
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}finally{
							
								}
								
							}
						});
				alert.setButton3("Toggle View", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
						if (map.isSatellite()){
							map.setSatellite(false);
							map.setStreetView(true);
						}else{
							map.setStreetView(false);
							map.setSatellite(true);
						}
						
						
					}
				});
				alert.show();
				return true;
			}

			return false;
		}
	}

	@Override
	public void onLocationChanged(Location l) {
		// TODO Auto-generated method stub
		lat = (int) (l.getLatitude() *1E6);
		longi = (int) (l.getLongitude()* 1E6);
		 
		GeoPoint ourLocation = new GeoPoint(lat, longi);
		OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
		CustomPinpoint custom = new CustomPinpoint(d, Map.this);
		custom.insertPinpoint(overlayItem);
		overlayList.add(custom);
		
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		Toast.makeText(Map.this, "StatusChanged" +arg0, Toast.LENGTH_SHORT).show();
	}
	
	public void findTasks()
	{
	
			//This routine is for reading the full contents of our key file until indicated
			FileInputStream fis = null;
			
			
			try 
			{
				fis = openFileInput("key");
				byte[] dataArray = new byte[fis.available()];
				while (fis.read(dataArray) != -1)
				{
					this.collected = new String(dataArray);
				}
			
			} 
			
			catch (FileNotFoundException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 	
			
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			finally
			{
					try 
					{
						fis.close();
					} 
					catch (IOException e) 
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
			//"INDICATED"
			
		
		}
}
